package com.pojotest.pojotest.controller;

import com.pojotest.pojotest.pojo.XboxGame;
import com.pojotest.pojotest.services.XboxService;
import com.pojotest.pojotest.tools.JsonResultObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/v1")
public class XboxController {

    /**
     * controller的职责是接收请求，然后调用service完成业务
     * 所以我们需要注入了service
     */
    @Autowired
    private XboxService xboxService;

    /**
     * 查询所有的游戏
     * GetMapping 说明方法只能使用get请求的方式访问
     *
     * @return
     */
    @GetMapping("/xboxs")
    public List<XboxGame> getAll() {
        List<XboxGame> xboxGameList = xboxService.getList();

        return xboxGameList;
    }

    /**
     * 取游戏单价超过500的游戏列表
     * @return
     */
    @GetMapping("/xboxs/height")
    public List<XboxGame> getHeight() {
        List<XboxGame> xboxGameList = xboxService.getHighPriceList();

        return xboxGameList;
    }

    /**
     * 在请求路径上接收参数
     *
     * @param id
     * @return
     */
    @GetMapping("/xbox/{id}")
    public JsonResultObject getById(@PathVariable int id) {
        XboxGame xboxGame = xboxService.findById(id);
        return new JsonResultObject<XboxGame>(xboxGame, "200", "get the record", "", "");
    }


    // 相同风格请求mapping（相同的访问url）在项目中只能出现一个
    @PostMapping("/xbox")
    public JsonResultObject add(XboxGame xboxgame) {
        boolean addResult = xboxService.add(xboxgame);
        if (addResult) {
            return new JsonResultObject(null, "200", "Add successfully", "", "");
        } else {
            return new JsonResultObject(null, "200", "", "20001", "fail to add");
        }
    }

    @PutMapping("/xbox")
    public JsonResultObject put(XboxGame xboxgame) {
        boolean addResult = xboxService.updateGame(xboxgame.getName(), xboxgame.getId());
        if (addResult) {
            return new JsonResultObject(null, "200", "Add successfully", "", "");
        } else {
            return new JsonResultObject(null, "200", "", "20001", "fail to add");
        }
    }

    @DeleteMapping("/xbox/{id}")
    public String removeById(@PathVariable int id) {
        boolean deleteResult = xboxService.deleteById(id);
        if (deleteResult) {
            return "delete it successfully";
        } else {
            return "failled, unable to delete it!";
        }
    }

}
